package com.zzyl.serve.job;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.serve.domain.AlertData;
import com.zzyl.serve.domain.AlertRule;
import com.zzyl.serve.domain.DeviceData;
import com.zzyl.serve.mapper.AlertDataMapper;
import com.zzyl.serve.mapper.DeviceDataMapper;
import com.zzyl.serve.mapper.DeviceMapper;
import com.zzyl.serve.mapper.NursingElderMapper;
import com.zzyl.serve.service.IAlertDataService;
import com.zzyl.serve.service.IAlertRuleService;
import com.zzyl.system.mapper.SysRoleMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 设备异常报警任务
 *
 * @author 16701
 */
@Component("alertJob")
public class AlertJob {
    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;
    @Autowired
    private IAlertRuleService alertRuleService;
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private IAlertDataService alertDataService;
    @Autowired
    private NursingElderMapper nursingElderMapper;
    @Autowired
    private DeviceDataMapper deviceDataMapper;
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private AlertDataMapper alertDataMapper;

    public void alertDeviceDataJob() {
        //前置校验:判断有没有报警规则
        List<AlertRule> list = alertRuleService.list();
        if (ObjectUtil.isEmpty(list)) {
            return;
        }
        //1.获取redis所有的设备数据
        List<Object> deviceDatas = redisTemplate.opsForHash().values(CacheConstants.IOT_DEVICE_LAST_DATA);
        if (ObjectUtil.isEmpty(deviceDatas)) {
            return;
        }
        for (Object deviceArrayData : deviceDatas) {
            //将每条设备的json字符串数据转成设备的数据列表
            List<DeviceData> deviceDataList = JSONUtil.toList(deviceArrayData.toString(), DeviceData.class);
            for (DeviceData deviceData : deviceDataList) {
                //2.处理每个物模型对应数据
                handleFunctionIdData(deviceData);
            }
        }
    }

    /**
     * 处理每个物模型对应的数据
     *
     * @param deviceData 物模型数据
     */
    public void handleFunctionIdData(DeviceData deviceData) {
        //判断设备上报时间是否过去了一分钟,如果超过60s说明该数据应该已经处理过了
        LocalDateTime alarmTime = deviceData.getAlarmTime();
        long seconds = LocalDateTimeUtil.between(alarmTime, LocalDateTime.now(), ChronoUnit.SECONDS);
        if (seconds >= 60) {
            return;
        }
        //判断是否有匹配的报警规则
        LambdaQueryWrapper<AlertRule> wrapper = Wrappers.<AlertRule>lambdaQuery()
                //启用
                .eq(AlertRule::getStatus, 1)
                //产品一致
                .eq(AlertRule::getProductKey, deviceData.getProductKey())
                //设备一致或者是全部设备都共有的规则
                .in(AlertRule::getIotId, deviceData.getIotId(), -1)
                //物模型一致
                .eq(AlertRule::getFunctionId, deviceData.getFunctionId());
        List<AlertRule> functionIdAlertRuleList = alertRuleService.list(wrapper);
        //3.处理每个规则，判断数据是否超过阈值
        for (AlertRule alertRule : functionIdAlertRuleList) {
            handleDataAlertRule(deviceData, alertRule);
        }
    }

    /**
     * 处理每个物模型的数据与报警规则的比对
     *
     * @param deviceData
     * @param alertRule
     */

    public void handleDataAlertRule(DeviceData deviceData, AlertRule alertRule) {
        //1.判断上报时间是否在报警规则有效期内
        String alertEffectivePeriod = alertRule.getAlertEffectivePeriod();
        String[] split = alertEffectivePeriod.split("~");
        LocalTime start = LocalTime.parse(split[0]);
        LocalTime end = LocalTime.parse(split[1]);
        LocalTime alarmTime = deviceData.getAlarmTime().toLocalTime();
        if (alarmTime.isBefore(start) || alarmTime.isAfter(end)) {
            return;
        }
        //2.判断数据是否超过报警阈值
        String duration = StringUtils.format(CacheConstants.IOT_ALERT_DURATION, deviceData.getIotId(), alertRule.getId());
        double value = Double.parseDouble(deviceData.getDataValue());
        if (">=".equals(alertRule.getOperator()) && value < alertRule.getValue()
                || "<".equals(alertRule.getOperator()) && value > alertRule.getValue()) {
            redisTemplate.delete(duration);
            return;
        }
        //3.报警前的其他判断
        //判断是否在沉默期间
        String silentPeriod = StringUtils.format(CacheConstants.IOT_ALERT_SILENT_PERIOD, deviceData.getIotId(), alertRule.getId());
        Object o = redisTemplate.opsForValue().get(silentPeriod);
        if (ObjectUtil.isNotEmpty(o)) {
            return;
        }
        //判断是否达到报警持续周期
        Long count = redisTemplate.opsForValue().increment(duration);
        if (count == null || count < alertRule.getDuration()) {
            return;
        }

        //4.确定报警
            //4.1报警前处理
        redisTemplate.opsForValue().set(silentPeriod, "silent...", alertRule.getAlertSilentPeriod(), TimeUnit.MINUTES);
        redisTemplate.delete(duration);
            //4.2保存报警数据
        AlertData data = new AlertData();
        BeanUtils.copyProperties(deviceData, data);
        data.setId(null);
        data.setAlertRuleId(alertRule.getId());
        data.setAlertReason(alertRule.getFunctionName() + alertRule.getOperator() + alertRule.getValue() + "达到" + alertRule.getDuration() + "次");
        data.setStatus(0);
            //确定是设备异常还是老人数据异常
        Integer alertDataType = alertRule.getAlertDataType();
        List<Long> ids = new ArrayList<>();
        if (alertDataType == 1) {
                //设备异常
            ids = sysRoleMapper.selectUserIdsByRoleName("维修工");
            data.setType(0);
        } else {
                //老人数据异常
            data.setType(1);
            if (deviceData.getLocationType() == 0) {
                  //随身设备，根据nursing_elder表查询老人相关联的护理员
                ids = nursingElderMapper.getNursingIdsByElderIdIotId(deviceData.getIotId());

            } else {
                  //固定设备,先查出入住信息，再查老人id,
                ids = nursingElderMapper.getNursingIdsByDeviceIotid(deviceData.getIotId());
            }
        }
            //插入数据
        for (Long id : ids) {
            data.setUserId(id);
            alertDataMapper.insert(data);
            data.setId(null);
        }
            //超级管理员也需要数据
        List<Long> adminIds = sysRoleMapper.selectUserIdsByRoleName("超级管理员");
        for (Long id : adminIds) {
            data.setUserId(id);
            alertDataMapper.insert(data);
            data.setId(null);
        }
    }

}
